/**
 * Created by sisi.chen on 2016/7/25.
 */
'use strict';
define(['echarts', 'echarts/chart/line',
    'echarts/chart/bar',
    'echarts/chart/radar'], function(echarts){
    var CustomCharts = function(element, options){
        this.$element = element;
        this.config = $.extend(true, {}, $.fn.customCharts.defaults , options);
        this.init();
        element.data('customCharts', this);
        return this.chartInstance;
    }

    /**
     * 初始化
     */
    CustomCharts.prototype.init = function(){
        //渲染 添加容器和legend区域
        this.render();
        this.event();
    }

    CustomCharts.prototype.event = function(){
        var _this = this;
        _this.$element.off("click", ".legend-area li").on("click", ".legend-area li", function(e){
            $(this).toggleClass("legend-active");
            $(this).toggleClass("legend-inactive");

            var legendSelected = $(this).hasClass("legend-active");
            var _legendName = $(this).attr("legendName");
            _this.chartInstance.component.legend.setSelected(_legendName, legendSelected);
        });

        _this.$element.off("click", ".legend-area .collapse-sign").on("click", ".legend-area .collapse-sign", function(e){
            $(this).toggleClass("fold");
            $(this).toggleClass("unfold");

            if ($(this).hasClass("unfold")){
                //展开
                _this.$legendUl.removeClass("legend-fold");
                _this.$legendUl.addClass("legend-unfold");
            } else {
                //折叠
                _this.$legendUl.addClass("legend-fold");
                _this.$legendUl.removeClass("legend-unfold");
                _this.$legendUl.get(0).scrollTop = '0px';
            }
        });

        _this.$element.off("mouseleave").on("mouseleave", function(){
            if ( _this.chartInstance.component.tooltip){
                _this.chartInstance.component.tooltip.hideTip();
            }
        })
    }

    CustomCharts.prototype.render = function(){
        this.$container = $('<div class="custom-chart-container"></div>');
        this.$chart = $('<div class="chart-area"></div>');
        this.$container.append(this.$chart);
        this.$element.append(this.$container);

        if (this.config.option.legend && this.config.option.legend.data && this.config.showCustomLegend){
            //显示自定义的legend
            this.config.option.legend.show = false;
            this.$chart.addClass("chart-with-legend");
            this.showCustomLegend = true;
        } else {
            this.showCustomLegend = false;
        }

        if (this.config.theme){
            this.chartInstance = echarts.init(this.$chart[0], this.config.theme);
        } else {
            this.chartInstance = echarts.init(this.$chart[0]);
        }

        this.chartInstance.setOption(this.config.option);
        this.renderLegend();
    }

    CustomCharts.prototype.renderLegend = function(){
        var _this = this;
        var _legend = this.config.option.legend;
        _this.$container.find(".legend-area").remove();
        if (this.showCustomLegend){
            _this.$legend = $('<div class="legend-area"></div>');
            _this.$container.append(_this.$legend);
            //因为显示自定义的legend，所以就不显示echart原生的legend
            //_legend.show = false;
            var selected = _legend.selected;
            _this.$legendUl = $("<ul></ul>");
            $.each(_legend.data, function(i, _legendName){
                var _showName = _legendName;
                if (_legend.formatter){
                    _showName = _legend.formatter(_legendName);
                }
                //是否开启当前图例
                var liC = "";
                if (undefined == selected || undefined == selected[_legendName] || selected[_legendName]){
                    liC = "legend-active";
                } else {
                    liC = "legend-inactive";
                }

                var _singleLegned = $('<li legendName="' + _legendName + '" class="' + liC + '" title="' + _showName + '"><span class="single-legend" ></span><span class="custom-chart-mark"></span></li>');
                if (_this.config.showLegendLabel){
                    var legendLabel = $('<label class="legend-label">' + _showName + ' </label>')
                    _singleLegned.append(legendLabel);
                }
                var legendColor = _this.chartInstance.component.legend.getColor(_legendName);
                _singleLegned.find(".single-legend").css("background-color", legendColor);
                _this.$legendUl.append(_singleLegned)
            });
            _this.$legend.append(_this.$legendUl)
            // var lengendT = _legend.data.length;
            // var sLegendW = 25 * lengendT;
            // if (sLegendW > _this.$legend.width()){
            //     var _collapseSign = $('<div class="collapse-sign fold"></div>');
            //     _this.$legend.append(_collapseSign)
            // }

            if (_this.$legendUl.height() > 30){
                //大于单行
                var _collapseSign = $('<div class="collapse-sign fold"></div>');
                _this.$legend.append(_collapseSign);
                _this.$legendUl.removeClass("legend-unfold");
                _this.$legendUl.addClass("legend-fold");
            }
        }
    }

    /**
     * 更新图标数据
     * @param _option
     */
    CustomCharts.prototype.update = function(_option){
        var _option = _option[0];
        this.chartInstance.clear();
        this.config.option = _option;
        if (this.config.option.legend && this.config.option.legend.data && this.config.showCustomLegend){
            //显示自定义的legend
            this.config.option.legend.show = false;
            this.$chart.addClass("chart-with-legend");
            this.showCustomLegend = true;
        } else {
            this.showCustomLegend = false;
        }
        this.chartInstance.setOption(_option);
        this.renderLegend();
    }


    CustomCharts.prototype.destroy = function(){
        this.chartInstance.clear();
        this.chartInstance.dispose();
        this.$element.empty();
    }

    $.fn.customCharts = function(option){
        var the = this.first();
        if (typeof option === 'object'){
            return new CustomCharts(the, option);
        } else if (typeof option == 'string'){
            var instance = the.data('customCharts');
            if (!instance){
                console.log("customCharts从未初始化")
                return;
            }
            var args = Array.prototype.slice.call(arguments, 1);
            var ret = instance[option](args);
            return ret;
        }

    }

    $.fn.customCharts.defaults = {
        showCustomLegend : true,
        showLegendLabel : true
    }

    return {
        /**
         * 联动
         */
        connect : function(_elements){
            if (!_elements || !_elements.length){
                return;
            }
            //图例 和 tooltip联动
            for (var i = 0; i < _elements.length ; i++){
                var c = $(_elements[i]).data('customCharts');
                if (!c){
                    console.log("customCharts从未初始化")
                    return;
                }
                var cI = c.chartInstance;
                $.each(_elements, function(j, _chart){
                    if (i != j){
                        var _chartI = $(_chart).data('customCharts');
                        if (!_chartI){
                            console.log("customCharts从未初始化")
                            return;
                        }
                        cI.connect(_chartI.chartInstance);
                    }
                })
            }

            _elements.off("mouseleave").on("mouseleave", function(){
                $.each(_elements, function(i, _element){
                    var _chartI = $(_element).data('customCharts');
                    if (_chartI){
                        if ( _chartI.chartInstance.component.tooltip){
                            _chartI.chartInstance.component.tooltip.hideTip();
                        }
                    }
                })
            })
        }
    }

});
